package com.xtck.ha.common.core.utils.uuid;

/**
 * @author zhouss
 * @date 2024/10/16
 **/
public class IdGenerator {
    private long workerId; // 工作机器 ID
    private long datacenterId; // 数据中心 ID
    private long sequence; // 序列号
    private long twepoch = 1288834974657L; // 起始时间戳（例如 2010-01-01）
    private long workerIdBits = 5L; // 工作机器 ID 占用位数
    private long datacenterIdBits = 5L; // 数据中心 ID 占用位数
    private long maxWorkerId = -1L ^ (-1L << workerIdBits); // 最大工作机器 ID
    private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); // 最大数据中心 ID
    private long sequenceBits = 12L; // 序列号占用位数

    private long workerIdShift = sequenceBits; // 工作机器 ID 左移位数
    private long datacenterIdShift = sequenceBits + workerIdBits; // 数据中心 ID 左移位数
    private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; // 时间戳左移位数
    private long sequenceMask = -1L ^ (-1L << sequenceBits); // 序列号掩码

    private long lastTimestamp = -1L; // 上次时间戳

    public IdGenerator() {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
        this.workerId = 0L;
        this.datacenterId = 0L;
        this.sequence = 0L;
    }

    public synchronized long nextId() {
        long timestamp = timeGen();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - twepoch) << timestampLeftShift) |
                (datacenterId << datacenterIdShift) |
                (workerId << workerIdShift) |
                sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }
}
